package com.alvin.demo.web;

import com.alvin.demo.common.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Slf4j
@Controller
@RequestMapping("/")
public class TestController {

	@ResponseBody
	@GetMapping("hello_cn_zh")
	public String hello_cn_zh() {
		return "Hello Spring Boot,是否中文乱码";
	}
	
	@GetMapping("uploadPage")
	public String uploadPage() {
		return "upload";
	}

	@Value("${file.uploadFolder}")
	private String uploadFolder;

	@ResponseBody
	@PostMapping(value = "/upload")
	public String uploadFile(@RequestParam MultipartFile file) {
		String originalFilename = file.getOriginalFilename();
		if (originalFilename == null || originalFilename.equals("")) {
			throw new RuntimeException("请先选择需要上传的文件");
		}
		File dir = new File(uploadFolder) ;
		if(dir.exists()&& !dir.isDirectory()) {
			throw new RuntimeException("上传目录错误！！");
		}
		if(!dir.exists()) {
			boolean flag = dir.mkdir();
			if (flag) {
				log.info("{} 创建成功" , uploadFolder);
			}else {
				log.info("{} 创建失败" , uploadFolder);
			}
		}
		
		String fileName = System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf(".")) ;
		String path = uploadFolder + "/" + fileName;
        File fileUpload = new File(path);
        try {
			file.transferTo(fileUpload);
			return path ;
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
			return "文件上传失败!!" ;
		}
	}
	
	@GetMapping("index.html")
	public String index() {
		return "index";
	}
	
    @GetMapping("/")
    public String index(ModelMap modelMap , HttpServletRequest request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()
                && !(authentication instanceof AnonymousAuthenticationToken)) {
            return "redirect:/index.html";
        }
		HttpSession session = request.getSession();
		String loginFailure = (String) session.getAttribute("loginFailure");
		if (loginFailure != null && loginFailure.equals("true")){
			modelMap.put("loginFailure", true);
		}else {
			modelMap.put("loginFailure", false);
		}
		session.removeAttribute("loginFailure");
		return "login";
    }

	@ResponseBody
	@Secured("ROLE_PRODUCT")
	@GetMapping("/add")
	public Result add() {
		return Result.ok("add" , "add success!");
	}

}
